<template>
  <view class="seal-selector" :class="{ 'seal-visible': visible }">
    <!-- 遮罩层 -->
    <view class="seal-mask" :class="{ 'seal-mask-show': visible }" @tap="handleClose"></view>

    <!-- 弹窗内容 -->
    <!-- 阻止内部点击事件冒泡到遮罩，避免点击弹窗内部任意处触发关闭 -->
    <view
      class="seal-modal"
      :class="{ 'seal-modal-show': visible }"
      @tap.stop
      @touchstart.stop
      @click.stop
    >
      <!-- 标题栏 -->
      <view class="seal-header">
        <text class="seal-title">选择公章</text>
        <text class="seal-close" @tap="handleClose">✕</text>
      </view>

      <!-- 印章列表 -->
      <view class="seal-content">
        <!-- 加载状态 -->
        <view v-if="loading" class="seal-loading">
          <text class="loading-text">加载中...</text>
        </view>

        <!-- 印章网格 -->
        <view v-else-if="sealList.length > 0" class="seal-grid">
          <view
            v-for="seal in sealList"
            :key="seal.id"
            class="seal-item"
            :class="{ 'seal-item-selected': selectedSeal?.id === seal.id }"
            @tap="selectSeal(seal)"
          >
            <!-- 印章图片 -->
            <view class="seal-image">
              <image
                v-if="getSealImageUrl(seal)"
                :src="getSealImageUrl(seal)"
                mode="aspectFit"
                class="seal-img"
                @error="handleImageError"
              />
              <view v-else class="seal-placeholder">
                <text class="seal-icon">🖊️</text>
              </view>
            </view>

            <!-- 印章信息 -->
            <view class="seal-info">
              <text class="seal-name">{{ seal.sealName }}</text>
              <view class="seal-badge">
                <text
                  class="badge-text"
                  :class="{
                    'badge-special': seal.sealType === 1,
                    'badge-normal': seal.sealType !== 1,
                  }"
                >
                  {{ seal.sealType === 1 ? '专用章' : '常规章' }}
                </text>
              </view>
              <text v-if="seal.companyName" class="seal-company">{{ seal.companyName }}</text>
            </view>

            <!-- 选中标记 -->
            <view v-if="selectedSeal?.id === seal.id" class="seal-check">
              <text class="check-icon">✓</text>
            </view>
          </view>
        </view>

        <!-- 空状态 -->
        <view v-else class="seal-empty">
          <text class="empty-icon">📭</text>
          <text class="empty-text">暂无可用公章</text>
        </view>
      </view>

      <!-- 底部按钮 -->
      <view class="seal-footer">
        <view class="footer-btn cancel-btn" @tap="handleClose">
          <text class="btn-text">取消</text>
        </view>
        <view
          class="footer-btn confirm-btn"
          :class="{ 'btn-disabled': !selectedSeal }"
          @tap="handleConfirm"
        >
          <text class="btn-text">确认选择</text>
        </view>
      </view>
    </view>

    <!-- 密码输入弹窗 -->
    <view class="password-dialog" :class="{ 'password-dialog-show': passwordDialogVisible }">
      <view class="password-mask" @tap="closePasswordDialog"></view>
      <view class="password-modal" @tap.stop>
        <view class="password-header">
          <text class="password-title">{{ passwordDialogTitle }}</text>
          <text class="password-close" @tap="closePasswordDialog">✕</text>
        </view>
        <view class="password-content">
          <view class="password-form-item">
            <text class="form-label">密码</text>
            <input
              v-model="passwordForm.password"
              type="password"
              :placeholder="selectedSeal?.hasPassword ? '请输入密码' : '请设置密码'"
              class="form-input"
              :password="!showPassword"
            />
            <text class="password-toggle" @tap="showPassword = !showPassword">
              {{ showPassword ? '隐藏' : '显示' }}
            </text>
          </view>
          <view v-if="passwordDialogTitle === '设置密码'" class="password-form-item">
            <text class="form-label">确认密码</text>
            <input
              v-model="passwordForm.confirmPassword"
              type="password"
              placeholder="请再次输入密码"
              class="form-input"
              :password="!showConfirmPassword"
            />
            <text class="password-toggle" @tap="showConfirmPassword = !showConfirmPassword">
              {{ showConfirmPassword ? '隐藏' : '显示' }}
            </text>
          </view>
        </view>
        <view class="password-footer">
          <view class="footer-btn cancel-btn" @tap="closePasswordDialog">
            <text class="btn-text">取消</text>
          </view>
          <view class="footer-btn confirm-btn" @tap="handlePasswordSubmit">
            <text class="btn-text">确定</text>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, watch } from 'vue'
import {
  getSealList,
  checkSealHasPassword,
  verifySealPassword,
  setSealPassword,
  type SealInfo,
} from '@/Api/document'

// ==================== Props & Emits ====================

interface Props {
  visible: boolean
}

interface Emits {
  (e: 'update:visible', value: boolean): void
  (e: 'confirm', seal: SealInfo): void
}

const props = withDefaults(defineProps<Props>(), {
  visible: false,
})

const emit = defineEmits<Emits>()

// ==================== 响应式数据 ====================

const loading = ref(false)
const sealList = ref<SealInfo[]>([])
const selectedSeal = ref<SealInfo | null>(null)

// 密码相关
const passwordDialogVisible = ref(false)
const passwordDialogTitle = ref('输入密码')
const passwordForm = ref({
  password: '',
  confirmPassword: '',
})
const showPassword = ref(false)
const showConfirmPassword = ref(false)

// ==================== 监听器 ====================

watch(
  () => props.visible,
  (newVal) => {
    if (newVal) {
      loadSealList()
      resetSelection()
    }
  },
)

// ==================== 方法 ====================

/**
 * 加载印章列表
 */
const loadSealList = async () => {
  loading.value = true
  try {
    const response = await getSealList()
    console.log('[SealSelector] 印章列表响应:', response)

    if (response.code === 200) {
      sealList.value = response.data || []
      console.log('[SealSelector] 加载印章列表成功，共', sealList.value.length, '个')
    } else {
      console.error('[SealSelector] 获取印章列表失败:', response.message)
      uni.showToast({
        title: response.message || '获取印章列表失败',
        icon: 'none',
      })
      sealList.value = []
    }
  } catch (error: any) {
    console.error('[SealSelector] 获取印章列表异常:', error)
    uni.showToast({
      title: error.message || '获取印章列表失败',
      icon: 'none',
    })
    sealList.value = []
  } finally {
    loading.value = false
  }
}

/**
 * 选择印章
 */
const selectSeal = (seal: SealInfo) => {
  selectedSeal.value = seal
  console.log('[SealSelector] 选择印章:', seal.sealName)
}

/**
 * 重置选择
 */
const resetSelection = () => {
  selectedSeal.value = null
}

/**
 * 确认选择
 */
const handleConfirm = async () => {
  if (!selectedSeal.value) {
    uni.showToast({
      title: '请选择一个公章',
      icon: 'none',
    })
    return
  }

  try {
    // 检查是否有密码
    const hasPasswordResponse = await checkSealHasPassword(selectedSeal.value.id)
    const hasPassword = hasPasswordResponse.code === 200 && hasPasswordResponse.data === true

    if (hasPassword) {
      // 有密码，需要输入密码验证
      passwordDialogTitle.value = '输入密码'
      passwordForm.value = { password: '', confirmPassword: '' }
      passwordDialogVisible.value = true
    } else {
      // 没有密码，需要设置密码
      passwordDialogTitle.value = '设置密码'
      passwordForm.value = { password: '', confirmPassword: '' }
      passwordDialogVisible.value = true
    }
  } catch (error: any) {
    uni.showToast({
      title: error?.message || '检查密码状态失败',
      icon: 'none',
    })
  }
}

/**
 * 处理密码提交
 */
const handlePasswordSubmit = async () => {
  if (!selectedSeal.value) {
    uni.showToast({
      title: '请先选择公章',
      icon: 'none',
    })
    return
  }

  // 验证输入
  if (!passwordForm.value.password) {
    uni.showToast({
      title: '请输入密码',
      icon: 'none',
    })
    return
  }

  if (passwordForm.value.password.length < 6 || passwordForm.value.password.length > 20) {
    uni.showToast({
      title: '密码长度在 6 到 20 个字符',
      icon: 'none',
    })
    return
  }

  const hasPassword = selectedSeal.value.hasPassword === true

  try {
    if (hasPassword) {
      // 验证密码
      const response = await verifySealPassword(selectedSeal.value.id, passwordForm.value.password)

      if (response.code === 200 && response.data === true) {
        uni.showToast({
          title: '密码验证成功',
          icon: 'success',
        })
        passwordDialogVisible.value = false
        emit('confirm', selectedSeal.value)
        handleClose()
      } else {
        uni.showToast({
          title: '密码错误，请重新输入',
          icon: 'none',
        })
        passwordForm.value.password = ''
      }
    } else {
      // 设置密码
      if (!passwordForm.value.confirmPassword) {
        uni.showToast({
          title: '请再次输入密码',
          icon: 'none',
        })
        return
      }

      if (passwordForm.value.password !== passwordForm.value.confirmPassword) {
        uni.showToast({
          title: '两次输入的密码不一致',
          icon: 'none',
        })
        return
      }

      const response = await setSealPassword(
        selectedSeal.value.id,
        passwordForm.value.password,
        passwordForm.value.confirmPassword,
      )

      if (response.code === 200) {
        uni.showToast({
          title: '密码设置成功，请再次输入密码确认',
          icon: 'success',
        })
        // 更新 hasPassword 状态
        selectedSeal.value.hasPassword = true
        // 清空表单，要求再次输入
        passwordDialogTitle.value = '输入密码'
        passwordForm.value = { password: '', confirmPassword: '' }
        // 不关闭弹窗，继续要求输入密码验证
      } else {
        uni.showToast({
          title: response.message || '设置密码失败',
          icon: 'none',
        })
      }
    }
  } catch (error: any) {
    uni.showToast({
      title: error?.message || '操作失败',
      icon: 'none',
    })
  }
}

/**
 * 关闭密码弹窗
 */
const closePasswordDialog = () => {
  passwordDialogVisible.value = false
  passwordForm.value = { password: '', confirmPassword: '' }
}

/**
 * 将 base64 字符串转换为 data URL
 * @param seal 公章信息对象
 * @returns data URL 字符串，如果不存在则返回空字符串
 */
const getSealImageUrl = (seal: SealInfo): string => {
  // 优先使用 sealBase64（新字段）
  if (seal.sealBase64) {
    // 如果已经是 data URL 格式，直接返回
    if (seal.sealBase64.startsWith('data:image/')) {
      return seal.sealBase64
    }
    // 否则添加 data URL 前缀
    return `data:image/png;base64,${seal.sealBase64}`
  }
  // 兼容旧字段 sealUrl
  if (seal.sealUrl) {
    return seal.sealUrl
  }
  return ''
}

/**
 * 关闭弹窗
 */
const handleClose = () => {
  emit('update:visible', false)
  setTimeout(() => {
    resetSelection()
  }, 300) // 等待动画完成再重置
}

/**
 * 图片加载错误处理
 */
const handleImageError = (event: any) => {
  console.warn('[SealSelector] 印章图片加载失败')
}
</script>

<style lang="scss" scoped>
.seal-selector {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 9999;
  /* 默认不可交互，visible 时启用 */
  pointer-events: none;

  &.seal-visible {
    pointer-events: auto;
  }
}

/* 遮罩层 */
.seal-mask {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0);
  transition: all 0.3s ease;
  pointer-events: none;

  &.seal-mask-show {
    background: rgba(0, 0, 0, 0.5);
    pointer-events: auto;
  }
}

/* 弹窗内容 */
.seal-modal {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  background: white;
  border-radius: 32rpx 32rpx 0 0;
  max-height: 80vh;
  display: flex;
  flex-direction: column;
  transform: translateY(100%);
  transition: transform 0.3s ease;
  z-index: 10000; /* 确保 modal 在遮罩之上 */
  pointer-events: auto; /* modal 内部可交互 */

  &.seal-modal-show {
    transform: translateY(0);
  }
}

/* 标题栏 */
.seal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 32rpx;
  border-bottom: 1rpx solid #f0f0f0;

  .seal-title {
    font-size: 36rpx;
    font-weight: bold;
    color: #333;
  }

  .seal-close {
    font-size: 48rpx;
    color: #999;
    line-height: 1;
    padding: 8rpx;
  }
}

/* 内容区域 */
.seal-content {
  flex: 1;
  overflow-y: auto;
  padding: 24rpx;
  min-height: 400rpx;
}

/* 加载状态 */
.seal-loading {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 400rpx;

  .loading-text {
    font-size: 28rpx;
    color: #999;
  }
}

/* 印章网格 */
.seal-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 24rpx;
}

/* 印章卡片 */
.seal-item {
  position: relative;
  border: 4rpx solid #e5e7eb;
  border-radius: 16rpx;
  padding: 24rpx;
  background: white;
  transition: all 0.3s ease;

  &.seal-item-selected {
    border-color: #409eff;
    background: #f0f9ff;
    box-shadow: 0 4rpx 16rpx rgba(64, 158, 255, 0.2);
  }

  .seal-image {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 160rpx;
    margin-bottom: 16rpx;
    background: #f8f9fa;
    border-radius: 12rpx;

    .seal-img {
      width: 100%;
      height: 100%;
    }

    .seal-placeholder {
      display: flex;
      justify-content: center;
      align-items: center;
      width: 100%;
      height: 100%;

      .seal-icon {
        font-size: 80rpx;
      }
    }
  }

  .seal-info {
    text-align: center;

    .seal-name {
      display: block;
      font-size: 28rpx;
      font-weight: 600;
      color: #303133;
      margin-bottom: 12rpx;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }

    .seal-badge {
      margin-bottom: 12rpx;

      .badge-text {
        display: inline-block;
        padding: 4rpx 16rpx;
        border-radius: 8rpx;
        font-size: 20rpx;

        &.badge-special {
          background: #fef0f0;
          color: #f56c6c;
        }

        &.badge-normal {
          background: #ecf5ff;
          color: #409eff;
        }
      }
    }

    .seal-company {
      display: block;
      font-size: 22rpx;
      color: #909399;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }
  }

  .seal-check {
    position: absolute;
    top: 16rpx;
    right: 16rpx;
    width: 48rpx;
    height: 48rpx;
    background: #409eff;
    border-radius: 50%;
    display: flex;
    justify-content: center;
    align-items: center;

    .check-icon {
      color: white;
      font-size: 28rpx;
      font-weight: bold;
    }
  }
}

/* 空状态 */
.seal-empty {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  height: 400rpx;
  gap: 16rpx;

  .empty-icon {
    font-size: 120rpx;
  }

  .empty-text {
    font-size: 28rpx;
    color: #909399;
  }
}

/* 底部按钮 */
.seal-footer {
  display: flex;
  gap: 24rpx;
  padding: 24rpx 32rpx;
  padding-bottom: calc(24rpx + env(safe-area-inset-bottom));
  border-top: 1rpx solid #f0f0f0;
  background: white;

  .footer-btn {
    flex: 1;
    height: 88rpx;
    border-radius: 16rpx;
    display: flex;
    justify-content: center;
    align-items: center;
    transition: all 0.3s ease;

    .btn-text {
      font-size: 32rpx;
      font-weight: 500;
    }

    &.cancel-btn {
      background: #f5f7fa;

      .btn-text {
        color: #606266;
      }

      &:active {
        opacity: 0.8;
      }
    }

    &.confirm-btn {
      background: #409eff;

      .btn-text {
        color: white;
      }

      &:active {
        opacity: 0.8;
      }

      &.btn-disabled {
        opacity: 0.5;
        pointer-events: none;
      }
    }
  }
}

/* 密码输入弹窗 */
.password-dialog {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 10000;
  pointer-events: none;

  &.password-dialog-show {
    pointer-events: auto;
  }
}

.password-mask {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0);
  transition: all 0.3s ease;
  pointer-events: none;
}

.password-dialog-show .password-mask {
  background: rgba(0, 0, 0, 0.5);
  pointer-events: auto;
}

.password-modal {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  background: white;
  border-radius: 32rpx 32rpx 0 0;
  max-height: 60vh;
  display: flex;
  flex-direction: column;
  transform: translateY(100%);
  transition: transform 0.3s ease;
  z-index: 10001;
  pointer-events: auto;
}

.password-dialog-show .password-modal {
  transform: translateY(0);
}

.password-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 32rpx;
  border-bottom: 1rpx solid #f0f0f0;

  .password-title {
    font-size: 36rpx;
    font-weight: bold;
    color: #333;
  }

  .password-close {
    font-size: 48rpx;
    color: #999;
    line-height: 1;
    padding: 8rpx;
  }
}

.password-content {
  padding: 32rpx;
  flex: 1;
  overflow-y: auto;

  .password-form-item {
    margin-bottom: 32rpx;
    position: relative;

    .form-label {
      display: block;
      font-size: 28rpx;
      color: #333;
      margin-bottom: 16rpx;
      font-weight: 500;
    }

    .form-input {
      width: 100%;
      height: 88rpx;
      padding: 0 24rpx;
      padding-right: 120rpx;
      border: 2rpx solid #e5e7eb;
      border-radius: 12rpx;
      font-size: 28rpx;
      background: #f8f9fa;
      box-sizing: border-box;
    }

    .password-toggle {
      position: absolute;
      right: 24rpx;
      top: 60rpx;
      font-size: 24rpx;
      color: #409eff;
      padding: 8rpx 16rpx;
    }
  }
}

.password-footer {
  display: flex;
  gap: 24rpx;
  padding: 24rpx 32rpx;
  padding-bottom: calc(24rpx + env(safe-area-inset-bottom));
  border-top: 1rpx solid #f0f0f0;
  background: white;

  .footer-btn {
    flex: 1;
    height: 88rpx;
    border-radius: 16rpx;
    display: flex;
    justify-content: center;
    align-items: center;
    transition: all 0.3s ease;

    .btn-text {
      font-size: 32rpx;
      font-weight: 500;
    }

    &.cancel-btn {
      background: #f5f7fa;

      .btn-text {
        color: #606266;
      }

      &:active {
        opacity: 0.8;
      }
    }

    &.confirm-btn {
      background: #409eff;

      .btn-text {
        color: white;
      }

      &:active {
        opacity: 0.8;
      }
    }
  }
}
</style>
